package com.sunday.shoufen.ui.index;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.shoufen.R;
import com.sunday.shoufen.adapter.IndexAdapter;
import com.sunday.shoufen.base.BaseApp;
import com.sunday.shoufen.base.BaseLocFragment;
import com.sunday.shoufen.entity.Ad;
import com.sunday.shoufen.entity.BizShop;
import com.sunday.shoufen.entity.City;
import com.sunday.shoufen.entity.IndexClassify;
import com.sunday.shoufen.entity.IndexData;
import com.sunday.shoufen.http.ApiClient;
import com.sunday.shoufen.ui.MainActivity;
import com.sunday.shoufen.ui.SearchShopListActivity;
import com.sunday.shoufen.ui.SelectCityListActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.app.Activity.RESULT_OK;

/**
 * Created by 刘涛 on 2017/10/17.
 */

public class IndexFragment extends BaseLocFragment {


    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.city_name)
    TextView cityName;

    private IndexAdapter adapter;
    private LinearLayoutManager layoutManager;
    private Integer cityId = null;
    private String latitude, longitude;
    private IndexData indexData;
    private List<Ad> adList = new ArrayList<>();
    private List<IndexClassify> shopCats = new ArrayList<>();
    private List<BizShop> activeShops = new ArrayList<>();
    private List<BizShop> hotShops = new ArrayList<>();


    public static IndexFragment newInstance() {
        IndexFragment fragment = new IndexFragment();
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isPrepared = true;
        lazyLoad();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_index, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        if (!isPrepared || !isVisible) {
            return;
        }
        initRefreshLayout();
        isPrepared = false;

    }

    private void initRefreshLayout() {
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new IndexAdapter(mContext, adList, shopCats, activeShops, hotShops);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).drawable(R.drawable.shape_divider).build());
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getData();
            }
        });

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (TextUtils.isEmpty(BaseApp.getInstance().getCityName()) && ((MainActivity) getActivity()).isRequestLocPermission()){
            requestLocation();
        }else if (!TextUtils.isEmpty(BaseApp.getInstance().getCityName())){
            getCityId();
        }
    }

    public void getData() {
        latitude = BaseApp.getInstance().getLatitude();
        longitude = BaseApp.getInstance().getLongitude();
        showLoadingDialog(0);
        Call<ResultDO<IndexData>> call = ApiClient.getApiAdapter().getIndexData(cityId, latitude, longitude);
        call.enqueue(new Callback<ResultDO<IndexData>>() {
            @Override
            public void onResponse(Call<ResultDO<IndexData>> call, Response<ResultDO<IndexData>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                refreshLayout.finishRefresh();
                if (response.body().getCode() == 0) {
                    indexData = response.body().getResult();
                    updateView();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<IndexData>> call, Throwable t) {
                dissMissDialog();
                refreshLayout.finishRefresh();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private void getCityId() {
        latitude = BaseApp.getInstance().getLatitude();
        longitude = BaseApp.getInstance().getLongitude();
        Call<ResultDO<City>> call = ApiClient.getApiAdapter().getCityId(latitude, longitude);
        call.enqueue(new Callback<ResultDO<City>>() {
            @Override
            public void onResponse(Call<ResultDO<City>> call, Response<ResultDO<City>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0 && response.body().getResult() != null) {
                    City city = response.body().getResult();
                    cityId = city.getId();
                    cityName.setText(city.getName());
                    BaseApp.getInstance().setCityName(city.getName());
                    BaseApp.getInstance().setCityId(cityId);
                    getData();
                } else {
                    getData();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<City>> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private void updateView() {
        if (indexData == null) {
            return;
        }
        cityName.setText(BaseApp.getInstance().getCityName());
        adList.clear();
        if (indexData.getAdsList() != null) {
            adList.addAll(indexData.getAdsList());
        }
        shopCats.clear();
        if (indexData.getShopCats() != null) {
            shopCats.addAll(indexData.getShopCats());
        }
        activeShops.clear();
        if (indexData.getNearShop() != null) {
            activeShops.addAll(indexData.getNearShop());
        }
        hotShops.clear();
        if (indexData.getHotShop() != null) {
            hotShops.addAll(indexData.getHotShop());
        }
        adapter.notifyDataSetChanged();

    }


    @OnClick({R.id.city_name, R.id.btn_search})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.city_name:
                intent = new Intent(mContext, SelectCityListActivity.class);
                startActivityForResult(intent, 0x111);
                break;
            case R.id.btn_search:
                intent = new Intent(mContext, SearchShopListActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == 0x111) {
            String city = data.getStringExtra("cityName");
            cityId = data.getIntExtra("cityId", 0);
            cityName.setText(city);
            BaseApp.getInstance().setCityName(city);
            BaseApp.getInstance().setCityId(cityId);
            getData();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onLocSucceed() {
        getCityId();
    }


    @Override
    public void onLocFailed() {
        requestLocation();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (TextUtils.isEmpty(BaseApp.getInstance().getCityName())) {
            requestLocation();
        }

    }
}
